//
//  UILabel.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/6/25.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//

import UIKit

extension UILabel {
    
    func setFont(font:CGFloat) {
        self.font = UIFont.systemFont(ofSize: font)
    }
    
    ///跑马灯效果
    func setScreenLabel(){
        
        //TODO: 取消跑马灯效果
        //开始动画  animationID
        //        UIView.beginAnimations("Marquee", context: nil)
        //
        //        //时间
        //        UIView.setAnimationDuration(10.0)
        //
        //        //曲线方式
        //        UIView.setAnimationCurve(.linear)
        //
        //        //判断是否需要反向执行
        //        UIView.setAnimationRepeatAutoreverses(false)
        //
        //        //重复次数
        //        UIView.setAnimationRepeatCount(10)
        //
        //        var frame = self.frame
        //        frame.origin.x = -frame.size.width
        //        self.frame = frame
        //        //与begin对应,结束动画
        //        UIView.commitAnimations()
        
    }
    
    func getTextRows() -> UInt {
        guard text != nil && text != "" else { return 0 }
        let labelHeight = sizeThatFits(CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))).height
        let rows = labelHeight / font.lineHeight
        
        return UInt(rows)
    }
    
    //判断文本标签的内容是否被截断
    var isTruncated: Bool {
        guard let labelText = text else {
            return false
        }
        
        //计算理论上显示所有文字需要的尺寸
        let rect = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let labelTextSize = (labelText as NSString)
            .boundingRect(with: rect, options: .usesLineFragmentOrigin,
                          attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): self.font]), context: nil)
        
        //计算理论上需要的行数
        let labelTextLines = Int(ceil(CGFloat(labelTextSize.height) / self.font.lineHeight))
        
        //实际可显示的行数
        var labelShowLines = Int(floor(CGFloat(bounds.size.height) / self.font.lineHeight))
        if self.numberOfLines != 0 {
            labelShowLines = min(labelShowLines, self.numberOfLines)
        }
        
        //比较两个行数来判断是否需要截断
        return labelTextLines > labelShowLines
    }
    
    
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
	guard let input = input else { return nil }
	return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
	return input.rawValue
}
